文档

AI写真:PHP SDK使用说明

更新时间:

使用PHP SDK调用AI写真的算法服务接口进行模型训练和写真制作。通过SDK,您可以定制LoRA模型,并根据模板制作写真。本文为您介绍使用PHP SDK调用接口之前的准备工作以及使用示例。

前提条件

  • 环境依赖:PHP版本为5.5或者更高版本。

  • 已准备好5-20张训练图片和1张模板图片,用于模型训练和写真制作。图片格式支持.jpg.jpeg.png等。

    • 如果进行单人写真制作,模板图片中包含单张人脸即可。多张训练图片中的人脸属于同一个人。

    • 如果进行多人写真制作,模板图片中需包含多张人脸,且人脸数量与模型训练的model_id数量一致。

    • 请确保图片的尺寸大于512×512像素。

准备工作

  1. 安装PHP,PHP版本为5.5或者更高版本。

  2. 安装Composer :

    1. Composer是PHP的一个依赖管理工具,用来管理PHP项目所依赖的代码库。安装方法:可参考Composer的使用说明文档

    2. 执行以下命令,下载最新的composer.phar。

      PHP -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
      PHP -r "if (hash_file('sha384', 'composer-setup.php') === 'e21205b207c3ff031906575712edab6f13eb0b361f2085f1f1237b7126d785e826a450292b6cfd1d64d92e6563bbde02') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
      PHP composer-setup.php
      PHP -r "unlink('composer-setup.php');"
    3. 任选一种方式,实现全局安装composer。

      1. 将composer安装在系统中

        sudo mv composer.phar /usr/local/bin/composer
      2. 把composer.phar目录加入环境变量。

        1. 将composer.phar所在目录写入.bashrc文件的末尾。

          export PATH=$PATH:/Path/to/composer.phar/dir
        2. 执行以下命令,初始化新环境

          source .bashrc

  3. 通过Composer安装依赖库。

    1. 在composer.json添加下列信息。

      {
        "repositories": [
          {
            "type": "git",
            "url": "https://github.com/aliyun/aliyun-pai-aiservice-php-sdk.git"
          }
        ],
        "require": {
          "aliyun/aliyun-pai-aiservice-php-sdk": "*@dev"
        }
      }
    2. 执行bash命令安装依赖库:

      composer install

    3. 若报github超时错误,可使用github镜像站:

      {
        "repositories": [
          {
            "type": "git",
            "url": "https://hub.nuaa.cf/aliyun/aliyun-pai-aiservice-php-sdk"
          }
        ],
          "require": {
            "aliyun/aliyun-pai-aiservice-php-sdk": "*@dev"
          }
      }

  1. 执行以下代码初始化Client。

    1. 使用以下Shell命令,将HOST、AppId和Token写入环境变量。在后续代码中会使用到这三个参数。

      export HOST="http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com"
      export AppId=xxx
      export Token=xxxxxxxxx

      参数

      描述

      HOST

      服务端地址:http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com

      AppId

      开通AI写真后,您可以直接在AI写真页面查看AppId。

      Token

      开通AI写真后,您可以直接在AI写真页面查看Token。

    2. 运行以下代码初始化Client。

      <?PHP
      namespace Swagger\Client;
      
      use Exception;
      use Swagger\Client\Configuration;
      use Swagger\Client\Api;
      use GuzzleHttp\Client;
      
      define("JOB_STATE_INIT", 0);
      define("JOB_STATE_WAIT", 1);
      define("JOB_STATE_SUCCESS", 2);
      define("JOB_STATE_FAILED", 3);
      
      require_once(__DIR__ . '/vendor/autoload.php');
      $config = Configuration::getDefaultConfiguration();
      // 从环境变量中获得 HOST,AppId,Token 参数
      $config->setHost(getenv("Host")); // host
      $config->setAppId(getenv("AppId")); // appid
      $config->setToken(getenv("Token")); // token
      
      $apiInstance = new Api\AigcImagesApi(
          new Client(),
          $config
      );
      ?>

调用代码示例

AI写真是一个资源消耗量较大的服务,主要包括模型训练和写真制作两个环节。模型训练通常需要几分钟的响应时间,而写真制作则只需要数十秒即可完成。AI写真的接口调用流程图如下:

image

各个接口的请求、响应代码示例和端到端的请求代码示例如下:

核验请求($apiInstance->aigcImagesCheck)

  • 请求代码示例如下:

    <?PHP
    namespace Swagger\Client;
    
    use Exception;
    use Swagger\Client\Configuration;
    use Swagger\Client\Api;
    use GuzzleHttp\Client;
    
    define("JOB_STATE_INIT", 0);
    define("JOB_STATE_WAIT", 1);
    define("JOB_STATE_SUCCESS", 2);
    define("JOB_STATE_FAILED", 3);
    
    require_once(__DIR__ . '/vendor/autoload.php');
    $config = Configuration::getDefaultConfiguration();
    // 从环境变量中获得 HOST,AppId,Token 参数
    $config->setHost(getenv("Host")); // host
    $config->setAppId(getenv("AppId")); // appid
    $config->setToken(getenv("Token")); // token
    
    $images = array("https://xxx1.jpg","https://xxx2.jpg");
      
    $apiInstance = new Api\AigcImagesApi(
        new Client(),
        $config
    );
    $response = $apiInstance->aigcImagesCheck($images);
    if ($response->getCode() != 'OK') {
        print("error message : ". $response->getMessage());
    }
    print($response);
    ?>

    参数说明如下:

    参数

    类型

    参数说明

    images

    array

    多个URL使用半角逗号(,)分隔。

  • 响应结果示例如下:

    {
        "request_id": "e81cbd62-b177-45bb-89d3-49735b0ac878",
        "code": "OK",
        "message": "success",
        "data": {
            "check_results": [
                {
                    "code": 1,
                    "frontal": false,
                    "message": "success",
                    "url": "https:/xxx/0.jpg"
                },
                {
                    "code": 1,
                    "frontal": true,
                    "message": "success",
                    "url": "https:/xxx/1.jpg"
                }
            ],
            "cost_time": 0.5031654834747314,
            "images": [
                "https:/xxx/0.jpg",
                "https:/xxx/1.jpg"
            ],
            "request_id": "e81cbd62-b177-45bb-89d3-49735b0ac878"
        }
    }
    

    返回结果中的各字段说明如下:

    字段

    类型

    描述

    requestId

    string

    请求流水号。

    code

    string

    请求状态码,是否完成,OK或者error。

    message

    string

    请求状态详细信息,成功为success,其他视具体返回内容。

    data

    array

    返回数据详情。

    data字段子字段说明:

    子字段名称

    类型

    参数说明

    checkResults

    array

    代表输入每张图片的检测结果。 每个图片对应一个字典,每个字典一共有三个key,分别是url、message与frontal,分别代表图片的URL,图片检测详情与是否为正面。

    costTime

    float

    本次API花费的服务端计算时长。

    images

    array

    核验的图片URL list。

    requestId

    string

    请求流水号(同上级request_id流水号)。

    check_results的message汇总:

    message

    状态码

    含义

    success

    1

    代表符合要求。

    Image decode error.

    2

    图像无法下载或者解码。

    Number of face is not 1.

    3

    人脸数量不为1。

    Image detect error.

    4

    人脸检测出错。

    Image encoding error.

    5

    人脸编码为特征向量出错。原因一般是无法检测到人脸。

    This photo is not the same person in photos.

    6

    如果不是上面的错误,只是这个错误,代表这张脸和其他脸不是同一张脸。此错误只出现于:输入10张以上的图片,存在和其他脸不同的图片。

模型发起训练($apiInstance->aigcImagesTrain)

  • 训练sd15:

    <?PHP
    namespace Swagger\Client;
    
    use Exception;
    use Swagger\Client\Configuration;
    use Swagger\Client\Api;
    use GuzzleHttp\Client;
    
    define("JOB_STATE_INIT", 0);
    define("JOB_STATE_WAIT", 1);
    define("JOB_STATE_SUCCESS", 2);
    define("JOB_STATE_FAILED", 3);
    
    require_once(__DIR__ . '/vendor/autoload.php');
    $config = Configuration::getDefaultConfiguration();
    // 从环境变量中获得 HOST,AppId,Token 参数
    $config->setHost(getenv("Host")); // host
    $config->setAppId(getenv("AppId")); // appid
    $config->setToken(getenv("Token")); // token
    
    $apiInstance = new Api\AigcImagesApi(
        new Client(),
        $config
    );
    
    
    $images = array("https://xxx/1.jpg", 
                    "https://xxx/0.jpg");
    $config=[] 
    $modelName = ''
      
    $response = $apiInstance->aigcImagesTrain($images, );
    if ($response->getCode() != 'OK') {
        print("error message : ". $response->getMessage());
        return;
    }
    
    print($response);
    $jobId = $response->getData()["job_id"];
    $modelId = $response->getData()["model_id"];
    print($jobId . "\n"); // job id
    print($modelId . "\n"); // model id , 用于生成接口
    
    ?>

    参数说明

    参数位置

    参数说明

    类型

    images

    训练的图片URL列表。

    array

    config

    参数配置,默认为空。

    array

    modelName

    自定义的模型名称,默认为空。

    string

  • 训练SDXL

    SDXL需要首先联系您的商务经理开通服务后,通过指定模型名称来进行使用。

    SDXL同时支持人像训练场景loRA训练。

    二者的训练通过configure中的参数指定。

    <?PHP
    namespace Swagger\Client;
    
    use Exception;
    use Swagger\Client\Configuration;
    use Swagger\Client\Api;
    use GuzzleHttp\Client;
    
    define("JOB_STATE_INIT", 0);
    define("JOB_STATE_WAIT", 1);
    define("JOB_STATE_SUCCESS", 2);
    define("JOB_STATE_FAILED", 3);
    
    require_once(__DIR__ . '/vendor/autoload.php');
    $config = Configuration::getDefaultConfiguration();
    // 从环境变量中获得 HOST,AppId,Token 参数
    $config->setHost(getenv("Host")); // host
    $config->setAppId(getenv("AppId")); // appid
    $config->setToken(getenv("Token")); // token
    
    $apiInstance = new Api\AigcImagesApi(
        new Client(),
        $config
    );
    
    // 训练图片
    $images = array("https://xxx/1.jpg", 
                    "https://xxx/0.jpg");
    
    $config=[
        'train_scene_lora_bool'=> False,
        'scene_lora_prompts'=> array(
            'a photography of a woman with long blonde hair and a white dress',
            'a photography of a woman in a pink dress posing for a picture',
            'a photography of a woman in a black dress with a white background',
            'a photography of a woman with a frilly collar and suspenders',
            'a photography of a woman with a white dress and a white headpiece'
        ),
    ] ;
    // # train_scene_lora_bool用于指定是否进行场景Lora训练。
    // # scene_lora_prompts对应每个场景Lora训练图片的文本。
    
    
    $modelName = 'train_xl' ;
      
    $response = $apiInstance->aigcImagesTrain($images, $config, $modelName);
    if ($response->getCode() != 'OK') {
        print("error message : ". $response->getMessage());
        return;
    }
    
    print($response);
    $jobId = $response->getData()["job_id"];
    $modelId = $response->getData()["model_id"];
    print($jobId . "\n"); // job id
    print($modelId . "\n"); // model id , 用于生成接口
    

    参数说明:

    参数位置

    参数说明

    类型

    images

    训练的图片URL列表。

    array

    modelName

    模型名称,用SDXL需要设置为train_xl。

    string

    config

    参数配置,默认为空。

    array

    configure内部参数名称

    参数说明

    类型

    是否必须

    默认值

    取值范围

    train_scene_lora_bool

    是否训练场景LoRA。

    bool

    False

    True, False

    scene_lora_prompts

    场景LoRA的提示词;

    训练场景LoRA必须输入,列表长度与images的URL一致。

    array

    []

  • 响应结果示例如下:

    {'code': 'OK',
     'data': {'job_id': xxxxx, 
       				'model_id': 'xxxxxxx-xxx-xxxxx'},
     'message': 'success',
     'request_id': 'de314ef5-114d-4db1-b54a-332d5300780b'}

    返回结果中的各字段说明如下:

    data字段说明

    参数名称

    参数说明

    类型

    job_id

    训练任务ID。

    int

    model_id

    本次模型训练的模型ID,为一串长度为36的字符串编码。

    String

    • 需要保存job_id来进行训练结果查询;

    • 需要保存model_id来对进行写真制作服务的请求。

训练结果查询($jobApi->getAsyncJob)

  • 请求代码示例如下:

    <?PHP
    namespace Swagger\Client;
    
    use Exception;
    use Swagger\Client\Configuration;
    use Swagger\Client\Api;
    use GuzzleHttp\Client;
    
    define("JOB_STATE_INIT", 0);
    define("JOB_STATE_WAIT", 1);
    define("JOB_STATE_SUCCESS", 2);
    define("JOB_STATE_FAILED", 3);
    
    require_once(__DIR__ . '/vendor/autoload.php');
    $config = Configuration::getDefaultConfiguration();
    // 从环境变量中获得 HOST,AppId,Token 参数
    $config->setHost(getenv("Host")); // host
    $config->setAppId(getenv("AppId")); // appid
    $config->setToken(getenv("Token")); // token
    
    $apiInstance = new Api\AigcImagesApi(
        new Client(),
        $config
    );
    
    
    $jobApi = new Api\AiServiceJobApi(new Client(), $config);
    
    $jobId = xxxx ;
      
    $jobResponse = $jobApi->getAsyncJob($jobId);
    $jobData = (array)$jobResponse->getData();
    $jobInfo = (array)$jobData["job"];
    ?>

    参数说明

    参数

    参数说明

    类型

    jobId

    请求服务时返回的job_id。

    int

  • 响应结果示例如下:

    • 当模型训练未执行完成时,响应结果如下:

    {
        "request_id": "28a42745-569f-4fde-abba-28e36ae2d73f",
        "code": "OK",
        "message": "success",
        "data": {
            "job": {
                "id": 2697635,
                "app_id": "xxxxxxxxx",
                "state": 1,
                "message": "model requesting",
                "Result": "",
                "type": "Image",
                "request_id": "acc2b189-1718-4aba-ab6b-8b9671f068e5",
                "model_id": 15,
                "create_time": "2023-11-28T16:10:14.058+08:00"
            }
        }
    }
    • 当模型训练执行完成后,响应结果如下:

    {
        "request_id": "c04520ba-7c1a-486c-988c-85e95323f1c7",
        "code": "OK",
        "message": "success",
        "data": {
            "job": {
                "id": 2697635,
                "app_id": "xxxxxxxxx",
                "state": 2,
                "message": "success",
                "Result": "{\"cost_time\":220.0366554260254,\"model_id\":\"xxxxxxxx\",\"states\":[{\"code\":1,\"frontal\":false,\"message\":\"success\",\"url\":\"https:\/\/train\/0.jpg\"},{\"code\":1,\"frontal\":true,\"message\":\"success\",\"url\":\"https:\/\/1.jpg\"}]}",
                "type": "Image",
                "request_id": "acc2b189-1718-4aba-ab6b-8b9671f068e5",
                "model_id": 15,
                "create_time": "2023-11-28T16:10:14.058+08:00"
            }
        }
    }

写真制作请求

  • 单人写真制作请求接口($apiInstance->aigcImagesCreate)

    • 预测sd15:

      <?PHP
      namespace Swagger\Client;
      
      
      use Swagger\Client\Configuration;
      use Swagger\Client\Api;
      use Swagger\Client\ApiException;
      use Swagger\Client\ObjectSerializer;
      use PHPUnit\Framework\TestCase;
      use GuzzleHttp\Client;
      
      define("JOB_STATE_INIT", 0);
      define("JOB_STATE_WAIT", 1);
      define("JOB_STATE_SUCCESS", 2);
      define("JOB_STATE_FAILED", 3);
      
      require_once(__DIR__ . '/vendor/autoload.php');
      $config = Configuration::getDefaultConfiguration();
      // 从环境变量中获得 HOST,AppId,Token 参数
      $config->setHost(getenv("Host")); // host
      $config->setAppId(getenv("AppId")); // appid
      $config->setToken(getenv("Token")); // token
      
      $apiInstance = new Api\AigcImagesApi(
          new Client(),
          $config
      );
      
         
      $modelid = 'xxxxxxx-xxxx-xxxx';
      $templateImage = 'https://xxx/template.jpg';
      $config=[];
      $modelName = '';
      $response = $apiInstance->aigcImagesCreate($modelid, $templateImage,$config, $modelName);
      assertEquals("OK", $response->getCode());
      if ($response->getCode() != 'OK') {
          print("error message : ". $response->getMessage());
          return;
      }
      $file = fopen("test.jpg","w");
      $img_byte = base64_decode($response->getData()["image"]);
      fwrite($file, $img_byte);
      
      fclose($file);
          
      ?>

      参数说明

      参数位置

      参数说明

      类型

      modelid

      LoRA模型名称,需要输入训练获得的model_id。

      当使用ipa_control_only模式时设置为""。

      string

      templateImage

      模板的URL路径。

      string

      modelName

      模型名称,默认输入空字符串。

      string

      config

      模型返回配置configure,默认输入空。

      array

      configure内部参数

      configure内部参数名称

      参数说明

      类型

      是否必须

      默认值

      取值范围

      lora_weights

      loRA强度。

      float

      0.90

      0.5~1.0

      first_denoising_strength

      第一次图像重建的强度。

      float

      0.45

      0.0~1.0

      second_denoising_strength

      第二次图像重建的强度。

      float

      0.30

      0.0~1.0

      more_like_me

      更像我的强度。

      float

      0.50

      0.0~1.0

      crop_face_preprocess

      是否裁剪图像后进行重建,大图建议开启。

      bool

      True

      True, False

      apply_face_fusion_before

      是否进行第一次人像融合。

      bool

      True

      True, False

      apply_face_fusion_after

      是否进行第二次人像融合。

      bool

      True

      True, False

      color_shift_middle

      是否进行第一次颜色校正。

      bool

      True

      True, False

      color_shift_last

      是否进行第二次颜色校正。

      bool

      True

      True, False

      background_restore

      是否重建背景。

      bool

      False

      True, False

      skin_retouching_bool

      是否进行皮肤平滑。

      开启后会进行皮肤的平滑与变亮,一般会使得图片更好看,但可能会导致皮肤过白,关闭后可以提高皮肤的质感。

      bool

      False

      True, False

      photo_enhancement_bool

      是否进行人像增强。

      开启后会进行人像修复或者超分,用于提高生成图片质量。

      bool

      True

      True, False

      photo_enhancement_method

      人像增强方式。

      photo_fix则是进行图像修复,可能会导致一些失真但会修复不合理的地方,可能会失去一些皮肤的质感。

      super_resolution则仅进行图像超分,更大幅度的保留原图。

      String

      photo_fix

      photo_fix, super_resolution

      makeup_transfer

      是否进行妆容迁移。

      开启后会进行妆容迁移,防止图片过素,但也可能导致图像有一些不像用户。

      bool

      False

      True, False

      makeup_transfer_ratio

      进行妆容迁移的强度。

      理论上值越大妆容迁移的比例就越大,生成的妆容也越像模板,但也可能导致图像有一些不像用户。

      float

      0.5

      0.0~1.0

      face_shape_match

      是否进行脸型的适配。

      开启后会减弱控制的强度,脸型与皮肤质感相比于之前会更加贴近用户。

      bool

      False

      True, False

      ipa_control

      是否进行ipa的控制。

      开启后会提高人像的相似度,但容易受到参考图片的影响。

      bool

      False

      True, False

      ipa_control_only

      开启后可以无需训练进行预测。

      开启后必须填入ipa_image_path。

      bool

      False

      True, False

      ipa_image_path

      参考人像的URL。

      开启ipa_control_only后必须填写。

      String

      None

      可下载的url

      ipa_weight

      ipa的控制强度。

      理论上,值越大时出图越像用户,但值太大容易导致图像失真。

      float

      0.5

      0.0~1.0

      style_name

      用于设置生成的风格。

      真实或者漫画风格。

      str

      Realistic

      Realistic,

      Anime

      lcm_accelerate

      用于设置生成的风格,是否进行lcm加速。

      bool

      False

      True, False

      sharp_ratio

      锐化程度,适当的值可以提高清晰度。

      过高会导致图片失真。

      float

      0.15

      0.0~1.0

      t2i_prompt

      如果期望使用文生图功能,则需要在这里设置提示词。

      如果设置了t2i_prompt则可以不传入模板的URL路径。

      String

      None

    • 预测SDXL

      SDXL需要首先联系您的商务经理开通服务后,通过指定模型名称来进行使用。

      <?PHP
      namespace Swagger\Client;
      
      
      use Swagger\Client\Configuration;
      use Swagger\Client\Api;
      use Swagger\Client\ApiException;
      use Swagger\Client\ObjectSerializer;
      use PHPUnit\Framework\TestCase;
      use GuzzleHttp\Client;
      
      define("JOB_STATE_INIT", 0);
      define("JOB_STATE_WAIT", 1);
      define("JOB_STATE_SUCCESS", 2);
      define("JOB_STATE_FAILED", 3);
      
      require_once(__DIR__ . '/vendor/autoload.php');
      $config = Configuration::getDefaultConfiguration();
      // 从环境变量中获得 HOST,AppId,Token 参数
      $config->setHost(getenv("Host")); // host
      $config->setAppId(getenv("AppId")); // appid
      $config->setToken(getenv("Token")); // token
      
      $apiInstance = new Api\AigcImagesApi(
          new Client(),
          $config
      );
      
         
      $modelid = 'xxxxxxxxxxxxx';
      $templateImage = "https://templateImage.jpg";
      $config=[];
      $modelName = 'create_xl';
      
      $response = $apiInstance->aigcImagesCreate($modelid, $templateImage,$config, $modelName);
      
      if ($response->getCode() != 'OK') {
          print("error message : ". $response->getMessage());
          return;
      }
       
      $file = fopen("test.jpg","w");
      $img_byte = base64_decode($response->getData()["image"]);
      fwrite($file, $img_byte);
      
      fclose($file);
      ?>

      参数说明

      参数位置

      参数说明

      类型

      modelid

      LoRA模型名称,需要输入训练获得的model_id。

      当使用ipa_control_only模式时设置为""。

      string

      templateImage

      模板的URL路径。

      当使用scene_lora或者prompt生成时设置为"t2i_generate"。

      string

      modelName

      模型名称,使用SDXL则需要设置为create_xl。

      string

      config

      模型返回配置configure,默认输入空。

      array

      configure内部参数

      configure内部参数名称

      参数说明

      类型

      是否必须

      默认值

      取值范围

      lora_weights

      LoRA的应用强度。

      理论上,值越大时出图越像用户,但值太大容易导致图像失真。

      float

      0.90

      0.5~1.0

      first_diffusion_steps

      第一次diffusion的步数。

      不建议修改,过低会导致图像失真。

      int

      50

      20-50

      first_denoising_strength

      第一次图像重建的强度。

      人物脸部的重建强度,越大进行的重建越多,理论上越大时出图越像用户,但值太大会导致图片不协调。

      float

      0.45

      0.0~1.0

      second_diffusion_steps

      第二次diffusion的步数。

      不建议修改,过低会导致图像失真。

      int

      30

      20-50

      second_denoising_strength

      第二次图像重建的强度。

      人物脸部边缘的重建强度,值太大会导致图片不协调。

      float

      0.30

      0.0~1.0

      more_like_me

      更像我的强度。

      人像融合的比例,值越大越像本人,值太大会导致图片真实感降低。

      float

      0.60

      0.0~1.0

      crop_face_preprocess

      是否裁剪图像后进行重建,大图建议开启。

      不建议调整。

      bool

      True

      True, False

      apply_face_fusion_before

      是否进行第一次人像融合。

      开启后会进行人像融合,不开启会导致相似度降低。

      bool

      True

      True, False

      apply_face_fusion_after

      是否进行第二次人像融合。

      开启后会进行人像融合,不开启会导致相似度降低。

      bool

      True

      True, False

      color_shift_middle

      是否进行第一次颜色校正。

      开启后会进行颜色矫正,使得输出图片的肤色更像模板。不开启则不会矫正,存在色偏的可能。

      bool

      True

      True, False

      color_shift_last

      是否进行第二次颜色校正。

      开启后会进行颜色矫正,使得输出图片的肤色更像模板。不开启则不会矫正,存在色偏的可能。

      bool

      True

      True, False

      background_restore

      是否重建背景。

      开启后会进行背景重建,理论上会让图片更自然,但会改变背景并且增加耗时。

      bool

      False

      True, False

      skin_retouching_bool

      是否进行皮肤平滑。

      开启后会进行皮肤的平滑与变亮,一般会使得图片更好看,但可能会导致皮肤过白,关闭后可以提高皮肤的质感。

      bool

      False

      True, False

      photo_enhancement_bool

      是否进行人像增强。

      开启后会进行人像修复或者超分,用于提高生成图片质量。

      bool

      True

      True, False

      photo_enhancement_method

      人像增强方式:

      photo_fix则是进行图像修复,可能会导致一些失真,但会修复不合理的地方,可能会失去一些皮肤的质感。

      super_resolution则仅进行图像超分,更大幅度地保留原图。

      String

      photo_fix

      photo_fix, super_resolution

      makeup_transfer

      是否进行妆容迁移。

      开启后会进行妆容迁移,防止图片过素,但也可能导致图像有一些不像用户。

      bool

      False

      True, False

      makeup_transfer_ratio

      进行妆容迁移的强度。

      理论上值越大妆容迁移的比例就越大,生成的妆容也越像模板,但也可能导致图像有一些不像用户。

      float

      0.5

      0.0~1.0

      ipa_control

      是否进行ipa的控制。

      开启后会提高人像的相似度,但容易受到参考图片的影响。

      bool

      False

      True, False

      ipa_control_only

      开启后可以无需训练进行预测。

      开启后必须填入ipa_image_path。

      bool

      False

      True, False

      ipa_image_path

      参考人像的URL。

      开启ipa_control_only后必须填入。

      String

      None

      可下载的URL

      ipa_weight

      ipa的控制强度。

      理论上越大时出图越像用户,但值太大容易导致图像失真。

      float

      0.5

      0.0~1.0

      lcm_accelerate

      用于设置生成的风格,是否进行lcm加速。

      bool

      False

      True, False

      sharp_ratio

      锐化程度,适当的值可以提高清晰度。

      过高会导致图片失真

      float

      0.15

      0.0~1.0

      scene_id

      如果期望使用scene lora则需要在这里设置scene id。

      scene id由训练获得,训练SDXL场景loRA时返回model id即为scene id。

      String

      None

      t2i_prompt

      如果期望使用文生图功能则需要在这里设置提示词。

      如果设置了t2i_prompt则可以不传入模板的URL路径。

      String

      None

  • 多人写真制作请求接口(aigc_images_create_by_multi_model_ids)

    <?PHP
    namespace Swagger\Client;
    
    
    use Swagger\Client\Configuration;
    use Swagger\Client\Api;
    use Swagger\Client\ApiException;
    use Swagger\Client\ObjectSerializer;
    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;
    
    define("JOB_STATE_INIT", 0);
    define("JOB_STATE_WAIT", 1);
    define("JOB_STATE_SUCCESS", 2);
    define("JOB_STATE_FAILED", 3);
    
    require_once(__DIR__ . '/vendor/autoload.php');
    $config = Configuration::getDefaultConfiguration();
    // 从环境变量中获得 HOST,AppId,Token 参数
    $config->setHost(getenv("Host")); // host
    $config->setAppId(getenv("AppId")); // appid
    $config->setToken(getenv("Token")); // token
    
    $apiInstance = new Api\AigcImagesApi(
        new Client(),
        $config
    );
    
    
    $modelids = array('xxxxxxx', 'xxxxxxx');
    $templateImage = 'https://xxx/multi_template.jpg';
    $config=[];
    $modelName = '';
    $response = $apiInstance->aigcImagesCreateByMultiModelIds($modelids, $templateImage, $config, $modelName);
    assertEquals("OK", $response->getCode());
    if ($response->getCode() != 'OK') {
        print("error message : ". $response->getMessage());
        return;
    }
    
    $file = fopen("test.jpg","w");
    $img_byte = base64_decode($response->getData()["image"]);
    fwrite($file, $img_byte);
    
    fclose($file);
    

    参数说明

    参数位置

    参数说明

    类型

    modelids

    所有用于生成图片的LoRA模型训练时的model_id组成的列表。

    array

    templateImage

    模板的URL路径。

    string

    modelName

    模型名称,默认输入空字符串。

    string

    config

    模型返回配置configure,默认输入空。

    array

    config内部参数名称

    config内部参数名称

    参数说明

    类型

    是否必须

    默认值

    取值范围

    lora_weights

    • LoRA的应用强度;

    • 理论上越大时出图越像用户,但值太大容易导致图像失真。

    float

    0.90

    0.5~1.0

    first_diffusion_steps

    • 第一次diffusion的步数。

    • 不建议修改,过低会导致图像失真。

    int

    50

    20-50

    first_denoising_strength

    • 第一次图像重建的强度;

    • 人物脸部的重建强度,越大进行的重建越多,理论上越大时出图越像用户,但值太大会导致图片不协调。

    float

    0.45

    0.0~1.0

    second_diffusion_steps

    • 第二次diffusion的步数。

    • 不建议修改,过低会导致图像失真。

    int

    30

    20-50

    second_denoising_strength

    • 第二次图像重建的强度;

    • 人物脸部边缘的重建强度,值太大会导致图片不协调。

    float

    0.30

    0.0~1.0

    more_like_me

    • 更像我的强度;

    • 人像融合的比例,值越大越像本人,值太大会导致图片真实感降低。

    float

    0.50

    0.0~1.0

    crop_face_preprocess

    • 是否裁剪图像后进行重建,大图建议开启;

    • 不建议调整。

    bool

    True

    True, False

    apply_face_fusion_before

    • 是否进行第一次人像融合;

    • 开启后会进行人像融合,不开启会导致相似度降低。

    bool

    True

    True, False

    apply_face_fusion_after

    • 是否进行第二次人像融合;

    • 开启后会进行人像融合,不开启会导致相似度降低。

    bool

    True

    True, False

    color_shift_middle

    • 是否进行第一次颜色校正;

    • 开启后会进行颜色矫正,使得输出图片的肤色更像模板。不开启则不会矫正,存在色偏的可能。

    bool

    True

    True, False

    color_shift_last

    • 是否进行第二次颜色校正;

    • 开启后会进行颜色矫正,使得输出图片的肤色更像模板。不开启则不会矫正,存在色偏的可能。

    bool

    True

    True, False

    background_restore

    • 是否重建背景;

    • 开启后会进行背景重建,理论上会让图片更自然,但会改变背景并且增加耗时。

    bool

    False

    True, False

    skin_retouching_bool

    • 是否进行皮肤平滑;

    • 开启后会进行皮肤的平滑与变亮,一般会使得图片更好看,但可能会导致皮肤过白,关闭后可以提高皮肤的质感。

    bool

    True

    True, False

    photo_enhancement_bool

    • 是否进行人像增强;

    • 开启后会进行人像修复或者超分,用于提高生成图片质量。

    bool

    True

    True, False

    photo_enhancement_method

    • 人像增强方式:

    • photo_fix则是进行图像修复,可能会导致一些失真但会修复不合理的地方,可能会失去一些皮肤的质感。

    • super_resolution则只进行图像超分,更大幅度的保留原图。

    str

    photo_fix

    photo_fix, super_resolution

    makeup_transfer

    • 是否进行妆容迁移;

    • 开启后会进行妆容迁移,防止图片过素,但也可能导致图像有一些不像用户。

    bool

    False

    True, False

    makeup_transfer_ratio

    • 进行妆容迁移的强度;

    • 理论上值越大妆容迁移的比例就越大,生成的妆容也越像模板,但也可能导致图像有一些不像用户。

    float

    0.5

    0.0~1.0

    face_shape_match

    • 是否进行脸型的适配;

    • 开启后会减弱控制的强度,脸型与皮肤质感相比于之前会更加贴近用户。

    bool

    False

    True, False

  • 响应结果示例如下:

    {
        "request_id": "42f8f213-2ae1-465d-964e-1a8de7e23357",
        "code": "OK",
        "message": "success",
        "data": {
            "cost_time": 13.644674062728882,
          "image": "....2wBDAAgGBgcGBQgHBwcJCQgK",
      		"model_id": "xxxxxxxxxx"
     		 },
    }

    返回结果中的各字段说明如下:

    字段

    参数说明

    类型

    request_id

    请求流水号。

    string

    code

    请求状态码,是否完成,OK或者error。

    string

    message

    请求状态详细信息,成功为success,其他视具体返回内容。

    string

    data

    返回create详情。

    array

    Data字段解析

    返回内容详情,array类型。内部字段说明如下:

    • model_id:用户的模型ID。

    • image:生成AI写真后的参考模板图片,Base64编码。

    • cost_time:写真制作消耗的时间,float类型。

  • 相关错误码说明

    • 请求服务错误码如下:

      HTTP状态码

      code

      message

      说明

      400

      PARAMETER_ERROR

      not found appid

      AppId填写错误。

      400

      EXCEEDED_QUOTA_ERROR

      exceeded quota

      账户调用次数额度用完。

      401

      PARAMETER_ERROR

      sign error

      Token填写错误。

      404

      PARAMETER_ERROR

      model not found

      对应模型服务未部署。

    • 结果查询错误码如下:

      HTTP状态码

      code

      message

      说明

      462

      error

      Invalid input data. Please check the input dict.

      输入数据解析错误。

      462

      error

      Image not provided. Please check the template_image.

      并未提供写真制作的模板图片。

      462

      error

      Prompts get error. Please check the model_id.

      检查提供的model_id格式。

      462

      error

      Roop image decord error. Pleace check the user's lora is trained or not.

      Roop图像不存在,请检查是否模型是否训练。

      462

      error

      Template image decord error. Please Give a new template.

      模板图片解码错误,请给一张新的模板。

      462

      error

      There is not face in template. Please Give a new template.

      模板图像不存在人脸,请给一个新的模板。

      462

      error

      Template image process error. Please Give a new template.

      模板图片预处理错误,请给一张新的模板。

      469

      error

      First Face Fusion Error, Can't get face in template image.

      第一次人脸融合出错。

      469

      error

      First Stable Diffusion Process error. Check the webui status.

      第一次Stable Diffusion处理出错。

      469

      error

      Second Face Fusion Error, Can't get face in template image.

      第二次人脸融合出错。

      469

      error

      Second Stable Diffusion Process error. Check the webui status.

      第二次Stable Diffusion处理出错。

      469

      error

      Please confirm if the number of faces in the template corresponds to the user ID.

      请检查所给的user id数量与人脸数量是否相符。

      469

      error

      Third Stable Diffusion Process error. Check the webui status.

      背景处理出错,请更换模板。

      500

      error

      Face id image decord error. Pleace check the user's lora is trained or not.

      Face id图片解码异常,请检查是否模型是否训练。

端到端流程示例代码

端到端流程的代码示例如下。当代码执行成功后,会在当前目录生成AI写真制作图片。

  • 常规链路(SD15)

    <?PHP
    namespace Swagger\Client;
    
    use Exception;
    use Swagger\Client\Configuration;
    use Swagger\Client\Api;
    use GuzzleHttp\Client;
    
    define("JOB_STATE_INIT", 0);
    define("JOB_STATE_WAIT", 1);
    define("JOB_STATE_SUCCESS", 2);
    define("JOB_STATE_FAILED", 3);
    
    require_once(__DIR__ . '/vendor/autoload.php');
    $config = Configuration::getDefaultConfiguration();
    // 从环境变量中获得 HOST,AppId,Token 参数
    $config->setHost(getenv("Host")); // host
    $config->setAppId(getenv("AppId")); // appid
    $config->setToken(getenv("Token")); // token
    
    $apiInstance = new Api\AigcImagesApi(
        new Client(),
        $config
    );
    
    // 训练图片
    $images = array("https://xxx/1.jpg",
                    "https://xxx/0.jpg");
    
    $response = $apiInstance->aigcImagesTrain($images);
    $jobId = $response->getData()["job_id"]; // 异步任务ID
    $modelId = $response->getData()["model_id"]; // 模型ID
    print("job_id=". $jobId . ", model_id=". $modelId. "\n");
    
    $jobApi = new Api\AiServiceJobApi(new Client(), $config);
    
    while(true) {
        $jobResponse = $jobApi->getAsyncJob($jobId);
        $jobData = (array)$jobResponse->getData();
        $jobInfo = (array)$jobData["job"];
        if ($jobInfo["state"] == JOB_STATE_WAIT || $jobInfo["state"] == JOB_STATE_INIT ) {
            print("job running\n");
        } else if ($jobInfo["state"] == JOB_STATE_SUCCESS) {
            print("job success\n");
            print($jobResponse);
            break;
        } else {
            print("job fail\n");
            print($jobResponse);
            throw new Exception("job fail");
        }
    
        // wait
        sleep(30);
    }
    
    // 模板图片
    $templateImage = "https://xxx/template.jpg";
    // 生成图片
    $response = $apiInstance->aigcImagesCreate($modelId, $templateImage);
    
    print($response);
    // 生成图片的 base64
    print($response->getData()["image"]);
    
    
    // 训练图片
    $modelIds = array("https://xxx/1.jpg",
                      "https://xxx/0.jpg");
    $templateImage = 'https://xxx/multi_template.jpg';
    $response = $apiInstance->aigcImagesCreateByMultiModelIds($modelIds, $templateImage);
    
    $file = fopen("test.jpg","w");
    $img_byte = base64_decode($response->getData()["image"]);
    fwrite($file, $img_byte);
    fclose($file);

    参数说明如下:

    参数

    描述

    images

    配置为训练模型使用的图片URL地址,多个URL地址之间使用半角逗号(,)分隔。

    templateImage

    模板图片的URL地址,包含单张人脸。用于单人写真制作。

    multiTemplateImage

    模板图片的URL地址,包含多张人脸,且人脸数量和所给的model_id一致。用于多人写真制作。

  • 常规链路(SDXL)

    SDXL需要首先联系您的商务经理开通服务后,通过指定模型名称来进行使用。

    <?PHP
    namespace Swagger\Client;
    
    use Exception;
    use Swagger\Client\Configuration;
    use Swagger\Client\Api;
    use GuzzleHttp\Client;
    
    define("JOB_STATE_INIT", 0);
    define("JOB_STATE_WAIT", 1);
    define("JOB_STATE_SUCCESS", 2);
    define("JOB_STATE_FAILED", 3);
    
    require_once(__DIR__ . '/vendor/autoload.php');
    $config = Configuration::getDefaultConfiguration();
    // 从环境变量中获得 HOST,AppId,Token 参数
    $config->setHost(getenv("Host")); // host
    $config->setAppId(getenv("AppId")); // appid
    $config->setToken(getenv("Token")); // token
    
    $apiInstance = new Api\AigcImagesApi(
        new Client(),
        $config
    );
    
    // 训练图片
    $images = array("https://xxx/1.jpg", 
                    "https://xxx/0.jpg");
    
    $response_check = $apiInstance->aigcImagesCheck($images);
    print($response_check);
    
    $response = $apiInstance->aigcImagesTrain($images, [],"train_xl");
    print($response);
    $jobId = $response->getData()["job_id"]; // 异步任务ID
    $modelId = $response->getData()["model_id"]; // 模型ID
    print("job_id=". $jobId . ", model_id=". $modelId. "\n");
    
    $jobApi = new Api\AiServiceJobApi(new Client(), $config);
    
    while(true) {
        $jobResponse = $jobApi->getAsyncJob($jobId);
        $jobData = (array)$jobResponse->getData();
        $jobInfo = (array)$jobData["job"];
        if ($jobInfo["state"] == JOB_STATE_WAIT || $jobInfo["state"] == JOB_STATE_INIT ) {
            print("job running\n");
        } else if ($jobInfo["state"] == JOB_STATE_SUCCESS) {
            print("job success\n");
            print($jobResponse);
            break;
        } else {
            print("job fail\n");
            print($jobResponse);
            throw new Exception("job fail");
        }
    
        // wait
        sleep(30);
    }
    
    // 模板图片
    $templateImage = "https://templateImage.jpg";
    // 生成图片
    $response = $apiInstance->aigcImagesCreate($modelId, $templateImage,[],"create_xl");
    
    print($response);
    // 生成图片的 base64
    print($response->getData()["image"]);
    
    $file = fopen("test.jpg","w");
    $img_byte = base64_decode($response->getData()["image"]);
    fwrite($file, $img_byte);
    
    fclose($file);

  • 无需训练,通过单参考图制作链路

    <?PHP
    namespace Swagger\Client;
    
    use Exception;
    use Swagger\Client\Configuration;
    use Swagger\Client\Api;
    use GuzzleHttp\Client;
    
    define("JOB_STATE_INIT", 0);
    define("JOB_STATE_WAIT", 1);
    define("JOB_STATE_SUCCESS", 2);
    define("JOB_STATE_FAILED", 3);
    
    require_once(__DIR__ . '/vendor/autoload.php');
    $config = Configuration::getDefaultConfiguration();
    // 从环境变量中获得 HOST,AppId,Token 参数
    $config->setHost(getenv("Host")); // host
    $config->setAppId(getenv("AppId")); // appid
    $config->setToken(getenv("Token")); // token
    
    $apiInstance = new Api\AigcImagesApi(
        new Client(),
        $config
    );
    
    
    // 模板图片
    $templateImage = "https://templateImage.jpg";
    $referenceImage = "https://referenceImage.jpeg";
    
    $modelId = "";
    $modelName = "";
    $config = [
        "ipa_control_only"=> true,
        "ipa_weight"=> 0.6,
        "ipa_image_path"=> $referenceImage,
    ];
    // 生成图片
    $response = $apiInstance->aigcImagesCreate($modelId, $templateImage, $config, $modelName);
    
    // 生成图片的 base64
    print($response->getData()["image"]);
    
     
    $file = fopen("test.jpg","w");
    $img_byte = base64_decode($response->getData()["image"]);
    fwrite($file, $img_byte);
    
    fclose($file);

  • 无需模板,通过提示词生成模板制作链路

    <?PHP
    namespace Swagger\Client;
    
    use Exception;
    use Swagger\Client\Configuration;
    use Swagger\Client\Api;
    use GuzzleHttp\Client;
    
    define("JOB_STATE_INIT", 0);
    define("JOB_STATE_WAIT", 1);
    define("JOB_STATE_SUCCESS", 2);
    define("JOB_STATE_FAILED", 3);
    
    require_once(__DIR__ . '/vendor/autoload.php');
    $config = Configuration::getDefaultConfiguration();
    // 从环境变量中获得 HOST,AppId,Token 参数
    $config->setHost(getenv("Host")); // host
    $config->setAppId(getenv("AppId")); // appid
    $config->setToken(getenv("Token")); // token
    
    $apiInstance = new Api\AigcImagesApi(
        new Client(),
        $config
    );
    $images = array("https://xxx/1.jpg", 
                    "https://xxx/0.jpg");
    
    $response = $apiInstance->aigcImagesTrain($images,[],"");
    print($response);
    $jobId = $response->getData()["job_id"]; // 异步任务ID
    $modelId = $response->getData()["model_id"]; // 模型ID
    print("job_id=". $jobId . ", model_id=". $modelId. "\n");
    
    $jobApi = new Api\AiServiceJobApi(new Client(), $config);
    
    while(true) {
        $jobResponse = $jobApi->getAsyncJob($jobId);
        $jobData = (array)$jobResponse->getData();
        $jobInfo = (array)$jobData["job"];
        if ($jobInfo["state"] == JOB_STATE_WAIT || $jobInfo["state"] == JOB_STATE_INIT ) {
            print("job running\n");
        } else if ($jobInfo["state"] == JOB_STATE_SUCCESS) {
            print("job success\n");
            print($jobResponse);
            break;
        } else {
            print("job fail\n");
            print($jobResponse);
            throw new Exception("job fail");
        }
    
        // wait
        sleep(30);
    }
    
    
    // 模板图片
    $templateImage = "https://templateImage.jpg";
    $t2i_prompt = "(portrait:1.5), 1girl, bokeh, bouquet, brown_hair, cloud, flower, hairband, hydrangea, lips, long_hair, outdoors, sunlight, white_flower, white_rose, green sweater, sweater, (cloth:1.0), (best quality), (realistic, photo-realistic:1.3), film photography, minor acne, (portrait:1.1), (indirect lighting), extremely detailed CG unity 8k wallpaper, huge filesize, best quality, realistic, photo-realistic, ultra high res, raw photo, put on makeup";
    
    $modelName = "";
    $configure = [
        "t2i_prompt" => $t2i_prompt
    ];
    // 生成图片
    $response = $apiInstance->aigcImagesCreate($modelId, $templateImage, $configure, $modelName);
    
    // 生成图片的 base64
    print($response->getData()["image"]);
    
     
    $file = fopen("test.jpg","w");
    $img_byte = base64_decode($response->getData()["image"]);
    fwrite($file, $img_byte);
    
    fclose($file);

  • 无需模板与训练,通过提示词与单参考图生成模板制作链路

    <?PHP
    namespace Swagger\Client;
    
    use Exception;
    use Swagger\Client\Configuration;
    use Swagger\Client\Api;
    use GuzzleHttp\Client;
    
    define("JOB_STATE_INIT", 0);
    define("JOB_STATE_WAIT", 1);
    define("JOB_STATE_SUCCESS", 2);
    define("JOB_STATE_FAILED", 3);
    
    require_once(__DIR__ . '/vendor/autoload.php');
    $config = Configuration::getDefaultConfiguration();
    // 从环境变量中获得 HOST,AppId,Token 参数
    $config->setHost(getenv("Host")); // host
    $config->setAppId(getenv("AppId")); // appid
    $config->setToken(getenv("Token")); // token
    
    $apiInstance = new Api\AigcImagesApi(
        new Client(),
        $config
    );
    
    // 模板图片
    $templateImage = "https://templateImage.jpg";
    $referenceImage = "https://referenceImage.jpeg";
    
    $t2i_prompt = "(portrait:1.5), 1girl, bokeh, bouquet, brown_hair, cloud, flower, hairband, hydrangea, lips, long_hair, outdoors, sunlight, white_flower, white_rose, green sweater, sweater, (cloth:1.0), (best quality), (realistic, photo-realistic:1.3), film photography, minor acne, (portrait:1.1), (indirect lighting), extremely detailed CG unity 8k wallpaper, huge filesize, best quality, realistic, photo-realistic, ultra high res, raw photo, put on makeup";
    $configure = [
        "t2i_prompt" => $t2i_prompt,
        "ipa_control_only"=> true,
        "ipa_weight"=> 0.6,
        "ipa_image_path"=> $referenceImage,
    ];
    
    
    // 生成图片
    $response = $apiInstance->aigcImagesCreate("", $templateImage, $configure, "");
    
    $file = fopen("test.jpg","w");
    $img_byte = base64_decode($response->getData()["image"]);
    fwrite($file, $img_byte);
    
    fclose($file);
    

相关文档

关于本SDK的更多详细内容,请参见PHP SDK github 开源代码库

  • 本页导读 (1)
文档反馈